package com.car.service.service.impl;

import com.car.service.entity.ChatMessage;
import com.car.service.mapper.ChatMessageMapper;
import com.car.service.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 聊天消息服务实现类
 */
@Service
public class ChatMessageServiceImpl implements ChatMessageService {
    
    @Autowired
    private ChatMessageMapper chatMessageMapper;
    
    @Override
    @Transactional
    public ChatMessage saveMessage(ChatMessage message) {
        Date now = new Date();
        if (message.getId() == null) {
            message.setCreateTime(now);
            message.setUpdateTime(now);
            message.setReadStatus(0); // 默认未读
            chatMessageMapper.insert(message);
        } else {
            message.setUpdateTime(now);
            chatMessageMapper.update(message);
        }
        return message;
    }
    
    @Override
    public List<ChatMessage> getMessagesBySessionId(String sessionId, int page, int size) {
        int offset = (page - 1) * size;
        return chatMessageMapper.selectBySessionId(sessionId, offset, size);
    }
    
    @Override
    @Transactional
    public void markMessagesAsRead(String sessionId, Long receiverId) {
        chatMessageMapper.updateReadStatus(sessionId, receiverId, 1);
    }
    
    @Override
    public int getUnreadMessageCount(String sessionId, Long receiverId) {
        return chatMessageMapper.countUnreadMessages(sessionId, receiverId);
    }
    
    @Override
    @Transactional
    public void deleteMessage(Long messageId) {
        chatMessageMapper.delete(messageId);
    }
} 